package cn.nawang.ebeim.client.version;

import java.util.Arrays;

/**
 * Given two sorted integer arrays A and B, merge B into A as one sorted array.
 * Note: You may assume that A has enough space (size that is greater or equal to m + n)
 * to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
 * <p>
 * Created by GanJc on 2016/2/25.
 */
public class MergeSortedArray {

    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3, 3, 4, 6, 9};
        int[] b = new int[]{1, 5, 6, 7, 9, 11, 18};
        mergeSortedArray(a, b);

        int[] c = new int[]{1, 2, 3, 3, 4, 6, 9};
        int[] d = new int[]{5, 6, 7, 9, 11, 18};
        mergeSortedArray(c, d);
    }

    public static void mergeSortedArray(int a[], int b[]) {
        int arr[] = new int[a.length + b.length];
        int ai = a.length - 1;
        int bi = b.length - 1;
        for (int i = a.length + b.length - 1; i >= 0; i--) {
            if (ai >= 0 && bi >= 0) {
                if (a[ai] > b[bi]) {
                    arr[i] = a[ai];
                    ai--;
                } else {
                    arr[i] = b[bi];
                    bi--;
                }
            } else if (ai >= 0) {
                arr[i] = a[ai];
                ai--;
            } else if (bi >= 0) {
                arr[i] = b[bi];
                bi--;
            }
        }
        System.out.println(Arrays.toString(arr));
    }


}
